package com.finstone.data.spider.eshop.processor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.finstone.data.spider.eshop.service.impl.EShopGoodsService;
import com.finstone.data.spider.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Html;
import us.codecraft.webmagic.selector.Selectable;

import com.finstone.data.spider.eshop.service.impl.EShopGoodsDetailService;

@Component
public class EShopGoodsProcessor implements PageProcessor {

    @Autowired
    private EShopGoodsDetailService eShopGoodsDetailService;
    @Autowired
    private EShopGoodsService eShopGoodsService;

    private Site site = Site.me().setCycleRetryTimes(3).setTimeOut(30000);

    public Site getSite() {
        site.addHeader("Referer", "http://s.lenovo.com.cn/?index=0&fromhomepage");
        site.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36");
        return site;
    }

    public void process(Page page) {

        String json_str = page.getJson().get();
        Map<String, Object> map = JsonUtils.fromJson(json_str);
        List<Map<String,Object>> list = (List<Map<String,Object>>)map.get("items");
        for(int i = 0;i<list.size();i++){
            String goodsId = list.get(i).get("code").toString();
            String price = list.get(i).get("price").toString();
            String name = list.get(i).get("name").toString();
            String temp_str = goodsId + ";" + price + ";" + name ;
            eShopGoodsDetailService.putTask(temp_str);
        }
        String url = page.getUrl().get();
        String[] url_params = url.split("&");
        Integer currentPage = 1 ;
        Integer pageSize = 0;
        for(int j = 0;j<url_params.length;j++){
            String[] param = url_params[j].toString().split("=");
            if(param[0].equals("page")){
                currentPage = Integer.parseInt(param[1].toString());
            }
            if(param[0].equals("pageSize")){
                pageSize = Integer.parseInt(param[1].toString());
            }
        }
        Integer totalNum = Integer.parseInt(map.get("totalNum").toString());
        Integer lastPage = (totalNum / pageSize) + 1;
        if (lastPage > currentPage) {
            String req_url = "http://s.lenovo.com.cn/search/lenovo?key=&innerKey=&filter=&stort=0&category=1a60e7bf-49e3-493e-8fa3-ad907226d92e&page=" + (currentPage + 1) + "&pageSize=24&isStock=false&leid=1.AX6l5Ph8vy0";
            Request request = new Request(req_url);
            page.addTargetRequest(request);
            return;
        }
    }
}
